package com.gitee.cirnochat.user.service.strategy;


import com.gitee.cirnochat.user.model.enums.UserStatus;
import com.gitee.cirnochat.user.service.strategy.impl.UserOfflineStateStrategy;
import com.gitee.cirnochat.user.service.strategy.impl.UserOnlineStateStrategy;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@RequiredArgsConstructor
public class UserStateStrategyContext {

    private final List<UserStateStrategy> strategyList;

    public void execute(Long userId, UserStatus status) {
        UserStateStrategy strategy = getStrategy(status);
        strategy.execute(userId);
    }

    /**
     * 根据状态匹配对应策略实现类
     */
    private UserStateStrategy getStrategy(UserStatus status) {
        return switch (status) {
            case ONLINE -> getStrategyByClass(UserOnlineStateStrategy.class);
            case OFFLINE -> getStrategyByClass(UserOfflineStateStrategy.class);
        };
    }

    private UserStateStrategy getStrategyByClass(Class<? extends UserStateStrategy> clazz) {
        return strategyList.stream()
                .filter(clazz::isInstance)
                .findFirst()
                .orElseThrow(() -> new IllegalStateException("未找到状态策略实现: " + clazz.getSimpleName()));
    }
}
